<template>
	<view class="page-wrap">
		<match-media :min-width="MAX_SIZEiZE">
			<navBar></navBar>
		</match-media>
		<match-media :max-width="MAX_SIZEiZE - 1">
			<cu-custom :title="$t('Page.mineWallet.zfbt')">
				<block slot="rightText">
					<uni-icons :class="{'refresh':isRefresh}" type="refreshempty" size="22" color="#fff"
						@click="checkOrderStatus"></uni-icons>
				</block>
			</cu-custom>
		</match-media>
		<view class="content">
			<pc-nav-bar :pageName="$t('Page.mineWallet.zfbt')">
				<image slot="right" :class="{'refresh':isRefresh}" src="@/static/image/Mine/Mywallet/refresh.png"
					mode="aspectFit" style="cursor: pointer;width: 20px;" @click="checkOrderStatus"></image>
			</pc-nav-bar>
			<view class="pay-cont">
				<view class="remain-time">
					{{$t('Page.user.sysj')}} {{timeout}}
				</view>
				<view class="tips">
					{{$t('Page.mine.sjsm')}}
				</view>
				<view class="order-sn">
					{{$t('Page.user.ddh')}}.{{payInfo.order_sn}}
				</view>
				<view class="qr-code-wrap">
					<uqrcode ref="QrCode" :start="false" canvasId="payQrCode" :value="payInfo.pix_qrcode" :size="150"
						:options="options">
					</uqrcode>
				</view>
				<waves class="btn copy-btn" @onTap="copyLink(payInfo.pix_qrcode)">
					{{$t('Page.user.fzpix')}}
				</waves>
				<view class="link">
					{{PayUrl}}
				</view>
				<waves class="btn copy-btn" @onTap="copyLink(payInfo.url)">
					{{$t('Page.mine.fzurl')}}
				</waves>
			</view>
		</view>

		<!-- 充值弹框 -->
		<uni-popup ref="statusChange" type="center" :is-mask-click="false">
			<view class="popup-cont">
				<view class="header">
					<view class="title">
						{{ $t('Page.mineWallet.ddztts') }}
					</view>
					<image class="close-icon" src="/static/image/close.png" @click="closePopup"></image>
				</view>
				<image v-if="preOrderInfo.status == 1" class="status-icon"
					:src="`/static/image/Mine/Mywallet/success-${theme}.png`">
				</image>
				<image v-else class="status-icon" :src="`/static/image/Mine/Mywallet/fail-${theme}.png`"></image>
				<view class="status-text">
					{{preOrderInfo.status == 1 ? 'Recharge successful' : 'Recharge failed'}}
				</view>
				<view class="row">
					<view>
						{{$t('Page.mineWallet.ddh')}}
					</view>
					<view>
						{{preOrderInfo.order_sn}}
					</view>
				</view>
				<view class="row">
					<view>
						{{$t('Page.mineWallet.czje')}}
					</view>
					<view>
						R${{preOrderInfo.price}}
					</view>
				</view>
				<button class="btn confrim-btn" @click="closePopup">
					{{ $t('Page.mineWallet.confirm') }}
				</button>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import pcNavBar from '@/components/pcNavBar/pcNavBar.vue'
	import cuCustom from '@/components/cu-custom/cuCustom.vue'
	import {
		mapState
	} from 'vuex'
	import {
		MAX_SIZEiZE
	} from '@/common/app.js'
	import {
		sendMessage
	} from '@/api/websocket.js'
	export default {
		components: {
			pcNavBar,
			cuCustom
		},
		data() {
			return {
				MAX_SIZEiZE,
				payInfo: {},
				options: {
					margin: 8
				},
				timer: null,
				timeout: '00:00',
				preOrderInfo: {},
				isRefresh: false,
				remainingTime: 1,
				callBackInfo: {}
			}
		},

		watch: {
			depositOrderInfo: {
				handler(newVal) {
					console.log("watch status: ", newVal);
					if (newVal?.status == 1) {
						this.toPayResult(1)
					}
				},
				deep: true
			}
		},
		computed: {
			...mapState({
				depositOrderInfo: state => state.app.depositOrderInfo,
				theme: state => state.app.theme,
			}),
			PayUrl() {
				if (this.payInfo.url) {
					return `${this.payInfo.url.slice(0,10)}${'*'.repeat(8)}${this.payInfo.url.slice(-4)}`
				}
			},
		},
		onLoad(option) {
			const item = JSON.parse(decodeURIComponent(option.item));
			this.payInfo = item
			console.log("this.payInfo: ", this.payInfo);
			// this.checkOrderStatus()
			this.countdown()
			uni.$on('checkcharge', (e) => {
				console.log("充值单状态改变了: ", e);
				const result = e instanceof Object;
				this.callBackInfo = e;
				if (!result) return;
				if (e.order_sn === this.payInfo.order_sn) {
					console.log('是同一笔订单', e.order_sn, this.payInfo.order_sn);
					this.toPayResult(e.status);
				} else {
					console.log('不是同一笔订单', e.order_sn, this.payInfo.order_sn);
					this.preOrderInfo = e;
					console.log('this.preOrderInfo: ', this.preOrderInfo);
					this.openPopup()
				}
			})
		},
		mounted() {
			this.$refs.QrCode.make();
		},
		destroyed() {
			clearTimeout(this.timer);
			this.timer = null;
		},
		onUnload() {
			// 移除监听事件  
			uni.$off('checkcharge');
		},

		methods: {
			openPopup() {
				this.$refs.statusChange.open('center');
			},
			closePopup() {
				this.$refs.statusChange.close();
			},
			// 返回充值页面
			handleConfirm() {
				uni.redirectTo({
					url: `/pages/user/wallet/wallet?inde=0`
				})
			},
			// 检查当前这笔订单的状态
			checkOrderStatus() {
				if (!this.payInfo.order_sn) return
				this.isRefresh = true
				const {
					CHECKCHARGE
				} = this.$api
				sendMessage({
					flag: CHECKCHARGE,
					content: {
						order_sn: this.payInfo.order_sn
					}
				})
				uni.$once(CHECKCHARGE, (res) => {
					const {
						code,
						data
					} = res
					console.log('主动检查订单状态通知', res)
					this.isRefresh = false
					// 倒计时没有结束时检查订单状态，这时订单状态可能没变，给一个请完成订单的提示
					if (this.remainingTime && code === 1 && data.status === 0) {
						uni.showToast({
							title: this.$t('Page.mineWallet.qxzf'),
							icon: 'none'
						})
					} else if (code === 1 && data.status === 1) {
						this.toPayResult(1)
					}
				})
			},

			toPayResult(status) {
				let item = {
					...this.payInfo,
					sn: this.payInfo.order_sn,
					status
				}
				uni.reLaunch({
					url: `/pages/Mine/wallet/components/rechargeResult?item=${encodeURIComponent(JSON.stringify(item))}`
				})
			},

			copyLink(data) {
				uni.setClipboardData({
					data,
					success: () => {
						uni.showToast({
							title: this.$t('Page.component.fzcg'),
							icon: 'none'
						})
					}
				});
			},

			countdown() {
				const endTime = new Date(+this.payInfo.timeout * 1000);
				this.timer = setTimeout(() => {
					const currentTime = new Date().getTime();
					const remainingTime = endTime - currentTime;
					this.remainingTime = remainingTime
					if (remainingTime >= 0) {
						const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
							.toString().padStart(2, '0');
						const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60)).toString()
							.padStart(2, '0');
						const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000).toString().padStart(2,
							'0');
						if (Number(hours) === 0) {
							this.timeout = `${minutes}:${seconds} s`
						} else {
							this.timeout = `${hours}:${minutes}:${seconds} s`
						}
						this.countdown()
					} else {
						this.timeout = `00:00 s`
						clearTimeout(this.timer)
						this.timer = null;
						if (this?.callBackInfo?.order_sn === this.payInfo.order_sn) {
							console.log('是同一笔订单269', this.callBackInfo.order_sn, this.payInfo.order_sn);
							this.toPayResult(this.callBackInfo.status);
							if (this.callBackInfo.status === 0) {
								this.toPayResult(0);
							} else if (this.callBackInfo.status === 1) {
								this.toPayResult(1)
							}
						} else {
							this.toPayResult(0)
						}
						// setTimeout(() => {
						// 	this.toPayResult(0)
						// }, 1000)
					}
				}, 1000);
			},
		}
	}
</script>

<style lang="scss" scoped>
	.btn {
		background: var(--bg-13);
		box-shadow: inset 0px 4px 4px 0px var(--box-shadow-color-1);
		color: var(--color-28);
		border-radius: 100px;
		cursor: pointer;
	}

	.page-wrap {
		min-height: 100vh;
		background: var(--bg-3);

		.content {
			width: 100%;
			height: calc(100vh - 44px - var(--status-bar-height)) !important;
			overflow-y: auto;
			padding: 10px 15px 15px;
			box-sizing: border-box;


			.pay-cont {
				width: calc(100% - 30px);
				margin: 0 auto;
				display: flex;
				flex-direction: column;
				align-items: center;
				background: var(--bg-9);
				padding: 20px 15px;
				box-sizing: border-box;
				border-radius: 15px;
				margin-top: 30px;

				.remain-time {
					width: 100%;
					text-align: center;
					background: var(--bg-36);
					border-radius: 15px;
					font-size: 15px;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					padding: 8px 0;
					color: #FFFFFF;
				}

				.tips {
					width: 100%;
					text-align: center;
					font-size: 16px;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #E7481A;
					margin-top: 20px;
				}

				.order-sn {
					width: 100%;
					text-align: center;
					font-size: 14px;
					font-family: PingFang SC-Medium, PingFang SC;
					font-weight: 500;
					color: #E87E45;
					margin-top: 20px;
				}

				.qr-code-wrap {
					margin-top: 20px;
				}

				.copy-btn {
					margin-top: 20px;
					padding: 8px 15px;
					font-size: 13px;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					min-width: 120px;
					box-sizing: border-box;
					text-align: center;
				}

				.link {
					margin-top: 20px;
					width: 100%;
					font-size: 14px;
					color: #FFFFFF;
					text-align: center;
					word-break: break-all;
				}

				.confrim-btn {
					width: 100%;
					text-align: center;
					padding: 8px 15px;
					margin-top: 30px;
					font-size: 13px;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
				}
			}
		}
	}

	@media screen and (min-width: 768px) {
		.page-wrap {
			padding-top: 70px;

			.content {
				width: 100%;
				height: calc(100vh - 70px) !important;
				overflow-y: auto;
				padding: 10px 30px 30px;
				box-sizing: border-box;
			}
		}
	}

	.popup-cont {
		width: 100%;
		padding: 15px 15px 30px;
		border-radius: 15px 15px 0 0;
		min-width: 375px !important;
		border-radius: 15px !important;
		padding-bottom: 20px !important;
		background: var(--bg-38);
		opacity: 0.95;
		color: #fff;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;

		.header {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 15px;

			.title {
				font-size: 16px;
				font-weight: bold;
				color: var(--color-17);
			}

			.close-icon {
				width: 25px;
				height: 25px;
				cursor: pointer;
			}
		}

		.status-icon {
			width: 70px;
			height: 70px;
			margin: 20px auto 10px;
		}

		.status-text {
			text-align: center;
			margin-bottom: 10px;
		}

		.row {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 40px;

			view {
				font-size: 15px;
				font-weight: bold;
				color: #FFFFFF;
				line-height: 18px;

				&:first-child {
					color: var(--color-34);
				}
			}

			.bouns {
				color: var(--color-1);
			}
		}


		.confrim-btn {
			height: 45px;
			line-height: 45px;
			text-align: center;
			font-size: 18px;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			margin-top: 30px;
			cursor: pointer;
			// color: var(--color-28);
		}
	}

	.refresh {
		animation: turntable 1s infinite;
	}

	@keyframes turntable {
		0% {
			transform: rotateZ(0deg);
		}

		100% {
			transform: rotateZ(360deg);
		}
	}
</style>